package com.wlcorp.forcazamis.dao.message.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ibatis.dao.client.DaoException;
import com.wlcorp.forcazamis.dao.message.IMessageDAO;
import com.wlcorp.forcazamis.domain.message.Message;

public class MessageDAOImpl extends HibernateDaoSupport implements IMessageDAO {

	public Message getMessageById(Long messageId) throws DaoException {
		return (Message) getHibernateTemplate().get(Message.class, messageId);
	}

	public List<Message> getMessageList(final Message message)
			throws DaoException {
		final StringBuffer queryString = new StringBuffer("select c from Message message where 1=1");
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException, SQLException {
				final Query query = session.createQuery(queryString.toString());
				if (null != message && null != message.getMinRownum()) {
					query.setFirstResult(message.getMinRownum());
					query.setMaxResults(message.getNumPerPage());
				}
				return query.list();
			}
		});
	}

	public void saveMessage(Message message) throws DaoException {
		getHibernateTemplate().saveOrUpdate(message);
	}

	public Long getMaxMessageId() throws DaoException {
		String hql="select max(message.messageId) from Message message";
		return ((Long)getHibernateTemplate().iterate(hql).next()).longValue();
	}

}
